/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package Homework6;

import Homework6.CustomEvents.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import javax.swing.BoxLayout;

/**
 *
 * @author Jakim
 */
public class TextRedactor extends Frame {

    // Private fields.
    private boolean _isChanged;
    private boolean _hasBufferCopyData;
    private TextArea _txtTextArea;
    private TextEditorMenu _textEditorMenuBar;
    private File _file;

    private char[] bufferCopy;

    public TextRedactor(){
        super("Text Redactor");
        final Frame thisFrame = this;
        this._textEditorMenuBar = TextEditorMenu.MenuBar;
        this._textEditorMenuBar.getMenuFile().addLoadFileListener(new ISaveLoadFileListener() {
            public void fileSaveEventOccured(SaveLoadFileEvent e) {
                _file = (File)e.getSource();
                saveFileFromTextAre();
                _isChanged = false;
                TextEditorMenu.MenuBar.getMenuFile().getMenuItemSave().setEnabled(_isChanged);

            }

            public void fileLoadEventOccured(SaveLoadFileEvent e) {
                _file = (File)e.getSource();
                loadFileToTextArea();
                _isChanged = false;
                TextEditorMenu.MenuBar.getMenuFile().getMenuItemSave().setEnabled(_isChanged);
            }
        });
        this._textEditorMenuBar.getMenuEdit().addFontChangeListener(new IEditTextListener() {

            public void penChangeFontOcured(EditTextEvent e) {
               CheckboxMenuItem cbMenuItem = (CheckboxMenuItem)e.getSource();
               if (cbMenuItem.getName().equals("Bold")){
                   if(cbMenuItem.getState()){
                       chageToBold();
                   }else{
                       resetBold();
                   }
               }else if(cbMenuItem.getName().equals("Italic")){
                   if(cbMenuItem.getState()){
                       chageToItalic();
                   }else{
                       resetItalic();
                   }
               }
            }
        });
        this._textEditorMenuBar.getMenuEdit().getMenuItemCopy().addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                bufferCopy = new char[_txtTextArea.getSelectedText().length()];
                bufferCopy = _txtTextArea.getSelectedText().toCharArray();
                _hasBufferCopyData = true;
                _textEditorMenuBar.getMenuEdit().getMenuItemPaste().setEnabled(_hasBufferCopyData);
            }
        });
        this._textEditorMenuBar.getMenuFile().getMenuItemExit().addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                getToolkit().getSystemEventQueue().postEvent(new WindowEvent(thisFrame, WindowEvent.WINDOW_CLOSING));
            }
        });
        this._textEditorMenuBar.getMenuEdit().getMenuItemPaste().addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
               int caretPosition = _txtTextArea.getCaretPosition();
               _txtTextArea.insert(String.copyValueOf(bufferCopy), caretPosition);
            }
        });
        this._textEditorMenuBar.getMenuEdit().getMenuItemCut().addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                bufferCopy = new char[_txtTextArea.getSelectedText().length()];
                bufferCopy = _txtTextArea.getSelectedText().toCharArray();
                _txtTextArea.replaceRange("", _txtTextArea.getSelectionStart(), _txtTextArea.getSelectionEnd());
                _hasBufferCopyData = true;
                _textEditorMenuBar.getMenuEdit().getMenuItemPaste().setEnabled(_hasBufferCopyData);
            }
        });
        this._textEditorMenuBar.getMenuEdit().getMenuItemClear().addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                _txtTextArea.setText("");
            }
        });
        this._textEditorMenuBar.getMenuEdit().getMenuItemClear().setEnabled(true);
        this._textEditorMenuBar.getMenuHelp().getMenuItemAbout().setEnabled(true);
        this._textEditorMenuBar.getMenuHelp().getMenuItemAbout().addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                showAboutWindow();
            }
        });
        
        this._txtTextArea = new TextArea(20, 50);
        this._txtTextArea.setText("");
        this._txtTextArea.addTextListener(new TextListener() {
            @Override
            public void textValueChanged(TextEvent e) {
                _isChanged = true;
                TextEditorMenu.MenuBar.getMenuFile().getMenuItemSave().setEnabled(_isChanged);
            }
        });
        this._txtTextArea.addMouseListener(new MouseAdapter() {

            @Override
            public void mouseReleased(MouseEvent e) {
               boolean isThereASelection = !_txtTextArea.getSelectedText().equals("");
               _textEditorMenuBar.getMenuEdit().getMenuItemCopy().setEnabled(isThereASelection);
               _textEditorMenuBar.getMenuEdit().getMenuItemCut().setEnabled(isThereASelection);
            }
        });

        this.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                if (!_isChanged){
                    System.exit(0);
                }else{
                    final Dialog d = new Dialog(thisFrame, "Предупреждение", true);
                    d.setLayout(new BoxLayout(d, BoxLayout.Y_AXIS));

                    Label lbl = new Label("Не сте запазили файла!\nЖелаете ли да го запазите?");
                    Panel panelButtons = new Panel();

                    Button btnYes = new Button("Да");
                    btnYes.addActionListener(new ActionListener() {

                        public void actionPerformed(ActionEvent e) {
                            d.setVisible(false);
                        }
                    });

                    Button btnNo = new Button("Не");
                    btnNo.addActionListener(new ActionListener() {

                        public void actionPerformed(ActionEvent e) {
                            System.exit(0);
                        }
                    });

                    panelButtons.add(btnYes);
                    panelButtons.add(btnNo);

                    d.add(lbl);
                    d.add(panelButtons);
                    d.pack();
                    d.setVisible(true);
                }
            }

        });
        this.setMenuBar(this._textEditorMenuBar);
        this.add(this._txtTextArea); 
        this.pack();
        this.setVisible(true);
    }

    public static void showAboutWindow(){
        final Frame frameAbout = new Frame();

        Label lbl = new Label("Ами не знам какво да напша за \"About\" меню опцията, за това няма да пиша нищо :)");

        frameAbout.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                frameAbout.setVisible(false);
            }
        });
        frameAbout.add(lbl);
        frameAbout.pack();
        frameAbout.setVisible(true);
    }

    public static void main(String args[]){
        new TextRedactor();
    }

    private void loadFileToTextArea(){
        char[] data;
        try {
            FileReader fileIn = new FileReader(this._file);
            int filesize = (int)this._file.length();
            data = new char[filesize];
            fileIn.read(data, 0, filesize);
            _txtTextArea.setText(String.valueOf(data));
        }catch (FileNotFoundException ex) {

        }
        catch (IOException ex) {

        }
    }

    private void saveFileFromTextAre() {
        this._file.setWritable(true);
        char[] data;
        try {
            data = new char[this._txtTextArea.getText().length()];
            data = this._txtTextArea.getText().toCharArray();
            FileWriter writeToFile = new FileWriter(this._file);
            writeToFile.write(data);
            writeToFile.close();
        }
        catch (FileNotFoundException ex) {
            System.err.println("The file can't be found");
        }catch (IOException ex) {
            System.err.println("The file can't be closed");
        }
    }

    private void chageToBold(){
        Font font = this._txtTextArea.getFont();
        this._txtTextArea.setFont(new Font(null, font.getStyle() | Font.BOLD, 14));
    }

    private void chageToItalic(){
        Font font = this._txtTextArea.getFont();
        this._txtTextArea.setFont(new Font(null, font.getStyle() | Font.ITALIC, 14));
    }

    private void resetBold(){
        Font font = this._txtTextArea.getFont();
        this._txtTextArea.setFont(new Font(null, font.getStyle() - Font.BOLD, 14));
    }
    
    private void resetItalic(){
        Font font = this._txtTextArea.getFont();
        this._txtTextArea.setFont(new Font(null, font.getStyle() - Font.ITALIC, 14));
    }
}
